<?php

class RecipeImage
{
    public static $config;

    public static function getConfig()
    {
        if(!isset(self::$config))
            self::$config=Yii::app()->params->recipeImage;
        return self::$config;
    }

    public static function getFilename($recipeId, $username, $type=null)
    {
        $config=self::getConfig();
        if(!isset($type)) {
            $types=array_keys($config['types']);
            $type=$types[0];
        }
        $str=__CLASS__.'-'.$recipeId.'-'.$username.'-'.$type;
        return md5($str).'.'.$config['types'][$type]['format'];
    }
    
    public static function toUrl($recipeId, $username, $type=null)
    {
        $filename=self::getFilename($recipeId,$username,$type);
        $config=self::getConfig();
        $url=sprintf($config['baseUrl'], hexdec($filename[0]));
        $dir=sprintf($config['dir'],$filename[0],$filename[1],$filename[2],$filename[3]);
        return $url.$dir.$filename;
    }
    
    public static function toPath($recipeId, $username, $type=null)
    {
        $filename=self::getFilename($recipeId,$username,$type);
        $config=self::getConfig();
        $path=sprintf($config['basePath'], hexdec($filename[0]));
        $dir=sprintf($config['dir'],$filename[0],$filename[1],$filename[2],$filename[3]);
        return $path.$dir.$filename;
    }
    
    public static function save($srcFile, $recipeId, $username)
    {
        $config=self::getConfig();
        $succFiles=array();
        $newFileSuffix='.new';
        foreach($config['types'] as $type) {            
            $filePath=self::toPath($recipeId, $username, $type);
            $operations=array_push($type['operations'], 
                array('save', 
                    'fileName'=>$filePath.$newFileSuffix, 
                    'format'=>isset($type['format'])?$type['format']:'jpg'));
        
            if(!ImageProcessor::process($srcFile,$operations,$type)) {
                foreach($succFiles as $filePath) {
                    unlink($filePath.$newFileSuffix);
                }
                return false;
            }
            $succFiles[]=$filePath;
        }
        
        foreach($succFiles as $filePath) {
            $newFilePath=$filePath.$newFileSuffix;
            cp($newFilePath, $filePath);
            unlink($newFilePath);
        }

        return true;
    }
    
    public static function delete($recipeId, $username)
    {
        $config=self::getConfig();
        foreach($config['types'] as $type) {            
            unlink(self::toPath($recipeId, $username, $type));
        }
    }
}

?>
